//必须引入的核心
import message from "element-plus/es/components/message/index.mjs"
import Recorder from "recorder-core"

//引入mp3格式支持文件；如果需要多个格式支持，把这些格式的编码引擎js文件放到后面统统引入进来即可
import "recorder-core/src/engine/mp3"
import "recorder-core/src/engine/mp3-engine"
//录制wav格式的用这一句就行
import "recorder-core/src/engine/wav"
let wave: any
const record: any = {
  RecordApp: null,
  recBlob: null,
  /**麦克风授权 */
  getPermission: (fn: Function, el: any) => {
    const newRec = Recorder({
      type: "wav",
      bitRate: 16,
      sampleRate: 16000, //阿里采样率16000
      onProcess: function (buffers: any, powerLevel: any, duration: any, bufferSampleRate: any) {
        if (wave) {
          wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate)
        }
      }
    })

    //打开录音，获得权限
    newRec.open(
      () => {
        record.RecordApp = newRec
        fn({ status: "success", data: "开启成功" })
        if (el) {
          //创建音频可视化图形绘制对象
          wave = Recorder.WaveView({ elem: el })
        }
      },
      (msg: any, isUserNotAllow: any) => {
        //用户拒绝了录音权限，或者浏览器不支持录音
        fn({ status: "fail", data: msg })
        console.log(isUserNotAllow)
        // const recMsg = (isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg
        message.error(msg || "无法录音")
      }
    )
  },
  /**开始录音 */
  startRecorder: () => {
    if (record.RecordApp && Recorder.IsOpen()) {
      record.RecordApp.start()
    }
  },
  /** 停止录音 */
  stopRecorder: (fn: Function) => {
    try {
      if (!record) {
        console.error("未打开录音")
        return
      }
      record.RecordApp.stop((blob: any, duration: any) => {
        console.log("录音成功", blob, "时长:" + duration + "ms")
        if (blob) {
          //blob就是我们要的录音文件对象，可以上传，或者本地播放
          //简单利用URL生成本地文件地址，此地址只能本地使用，比如赋值给audio.src进行播放，赋值给a.href然后a.click()进行下载（a需提供download="xxx.mp3"属性）
          const localUrl = (window.URL || window.webkitURL).createObjectURL(blob)
          localUrl
          record.recBlob = blob
          // const formData = new FormData()
          // formData.append("audio", blob)
          fn({ loading: true, url: localUrl, blob: blob })
        }
        /* eslint-enable */
        record.RecordApp.close()
        record.RecordApp = null
      })
    } catch (err) {
      fn({ err: err })
      console.error("结束录音出错：" + err)
      record.RecordApp.close()
      record.RecordApp = null
    }
  },

  /**关闭录音，释放麦克风资源 */
  destroyRecorder: () => {
    if (record.RecordApp) {
      record.RecordApp.close()
      record.RecordApp = null
    }
  },

  /**暂停 */
  pauseRecorder: () => {
    if (record.RecordApp) {
      record.RecordApp.pause()
    }
  },
  /**恢复继续录音 */
  resumeRecorder: () => {
    if (record.RecordApp) {
      record.RecordApp.resume()
    }
  },

  // 波形容器
  waveDom: (element: any) => {
    return element
  }
}

export default record
